package com.math.aistudykbr.service.impl;

import com.math.aistudykbr.mapper.QAMapper;
import com.math.aistudykbr.pojo.entity.AnalysisResult;
import com.math.aistudykbr.pojo.entity.AsyncTask;
import com.math.aistudykbr.pojo.entity.DocumentChunk;
import com.math.aistudykbr.pojo.entity.LearningMaterial;
import com.math.aistudykbr.service.AiAnalysisService;
import com.math.aistudykbr.service.AsyncTaskService;
import com.math.aistudykbr.service.FileParserService;
import com.math.aistudykbr.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class AsyncTaskServiceImpl implements AsyncTaskService {

    // 文件解析服务
    private final FileParserService fileParserService;

    // AI分析服务
    private final AiAnalysisService aiAnalysisService;

    // 使用线程安全的ConcurrentMap存储异步任务（Key: 任务ID，Value: 任务对象）
    private final ConcurrentMap<String, AsyncTask> taskStore  = new ConcurrentHashMap<>();

    private final QAMapper qaMapper;

    @Override
    public AsyncTask createAsyncTask(MultipartFile file) {
        // 生成唯一任务ID
        String taskId = UUID.randomUUID().toString();

        // 创建初始状态为PENDING的异步任务对象
        AsyncTask task = new AsyncTask(taskId, "PENDING", file.getOriginalFilename(), file, null, null, null, null, null);

        // 将任务存入内存存储
        taskStore.put(taskId, task);

        return task;
    }

    @Async("analysisTaskExecutor")  // 使用指定的线程池执行异步方法
    @Override
    public void executeAnalysis(String taskId) {
        AsyncTask task = taskStore.get(taskId);
        try {
            task.setStatus("PROCESSING");   // 更新任务状态为处理中

            log.info("开始处理异步任务：{}，文件名：{}", taskId, task.getFileName());

            // 解析上传的文档文件为结构化数据块
            List<DocumentChunk> documentChunks = fileParserService.parseDocument(task.getFile());

            // 调用AI服务生成学习计划分析结果和思维导图
            Map<String, String> resultUrls = aiAnalysisService.generateLearningPlan(documentChunks);
            
            // 设置XMIND和PNG链接
            task.setXmindUrl(resultUrls.get("xmindUrl"));
            task.setPngUrl(resultUrls.get("pngUrl"));
            
            log.info("思维导图生成成功 - XMind: {}, PNG: {}", task.getXmindUrl(), task.getPngUrl());

            // 保存为学习材料
            LearningMaterial material = new LearningMaterial();
            material.setContent(documentChunks.stream()
                    .map(DocumentChunk::getContent)
                    .collect(Collectors.joining("\n"))); // 存储原始解析后的文档内容
            material.setTitle(task.getFileName());
            material.setStatus(1);
            material.setUserId(UserContext.getUser());
            qaMapper.saveMaterial(material);
            Long materialId = qaMapper.getMaterialIdByTitleAndUserId(UserContext.getUser(), task.getFileName());

            // 设置AI消息
            task.setAiResponse("生成成功");

            // 更新任务状态为已完成
            task.setMaterialId(materialId);
            task.setStatus("COMPLETED");
        }catch (Exception e) {
            task.setStatus("FAILED");   // 捕获异常更新任务状态为失败
            task.setErrorMessage(e.getMessage());
            log.error("异步任务执行失败：{}", e.getMessage());
        }
    }

    @Override
    public AnalysisResult getAnalysisResult(String taskId) {
        // TODO: 待实获现取分析结果的具体逻辑
        return null;
    }
}
